<script setup>

import {ref, onMounted} from "vue";
import axios from "axios";
import router from "@/router";
import {ElMessage, ElMessageBox} from "element-plus";
import {useCartStore} from "@/store/cartStore";

const activeName = ref("all")

const user = JSON.parse(sessionStorage.getItem("CurUser"))
// 订单列表
const orderList = ref([])
// 获取订单列表
const getOrderList = () => {
  if (user) {
    axios.get('/dressup/order/allOrder', {
      params: {
        userId: user.userId
      }
    }).then(res => {
      orderList.value = res.data.data;
    })
  }
}

// 根据订单状态检索
const getOrdersByStatus = (status) => {
  if (user) {
    axios.get('/dressup/order/ordersByStatus', {
      params: {
        userId: user.userId,
        status: fomartPayState(status)
      }
    }).then(res => {
      orderList.value = res.data.data;
    })
  }
}

const tabChange = (status) => {
  if (status === 'all') {
    getOrderList()
  }
  else {
    getOrdersByStatus(status)
  }
}

onMounted(() => {
  getOrderList()
})

// 创建格式化函数
const fomartPayState = (payState) => {
  switch (payState) {
    case "all":
      return '全部订单'
    case "unpay":
      return "待支付"
    case "deliver":
      return "待发货"
    case "receiver":
      return "待收货"
    case "comment":
      return "待评价"
    case "complete":
      return "已完成"
    case "cancel":
      return "已取消"
  }
}

// 继续支付
const pay = (orderNo) => {
  router.push(`/pay/${orderNo}`)
}

const cartStore = useCartStore()
// 再次购买
const buyAgain =  (orderItems) => {
  orderItems.forEach(item => {
    cartStore.addCart(user.userId, item.clNo, item.clNum, item.clName, item.clPrice)
  })
}

// 取消订单
const cancelOrder = (orderNo) => {
  ElMessageBox.confirm(
      '您确定要取消订单吗？',
      '取消订单',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass:'ExitConfirmButton'
      }
  ).then(() => {
    axios.post('/dressup/order/changeOrderStatus', null, {
      params: {
        orderNo: orderNo,
        status: '已取消'
      }
    }).then(() => {
      activeName.value = "cancel"
      getOrdersByStatus(activeName.value)
      ElMessage.success('订单已取消')
    })
  }).catch(() => {})
}

// 确认收货
const receiveOrder = (orderNo) => {
  ElMessageBox.confirm(
      '确定已收到商品？',
      '确认收货',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass:'ExitConfirmButton'
      }
  ).then(() => {
     axios.post('/dressup/order/changeOrderStatus', null, {
      params: {
        orderNo: orderNo,
        status: '待评价'
      }
    }).then(() => {
       activeName.value = "comment"
       getOrdersByStatus(activeName.value)
       ElMessage.success('确认收货成功')
    })
  }).catch(() => {})
}

</script>

<template>
  <div class="order-container">
    <el-tabs class="my-tabs" :key="activeName" @tab-change="tabChange" v-model="activeName">
      <!-- tab切换 -->
      <el-tab-pane name="all" label="全部订单"/>
      <el-tab-pane name="unpay" label="待支付"/>
      <el-tab-pane name="deliver" label="待发货"/>
      <el-tab-pane name="receiver" label="待收货"/>
      <el-tab-pane name="comment" label="待评价"/>
      <el-tab-pane name="complete" label="已完成"/>
      <el-tab-pane name="cancel" label="已取消"/>
      <div class="main-container">
        <el-scrollbar height="524px">
          <div v-if="orderList.length === 0" class="holder-container">
            <el-empty description="暂无订单数据" />
          </div>
          <div v-else class="order-item" v-for="order in orderList">
            <div class="head">
              <span>订单编号：{{ order.orderNo }}</span>
            </div>
            <div class="body">
              <div class="column goods">
                <ul>
                  <li v-for="orderItem in order.orderItems">
                    <router-link :to=" `/goodsDetail/${orderItem.clNo}`" class="goodsItem">
                      <img :src="`http://localhost:8080/images/clothes/` + orderItem.clNo + `.jpg`" alt="" />
                    </router-link>
                    <div class="info">
                      <p class="name ellipsis-2">
                        {{ orderItem.clName }}
                      </p>
                    </div>
                    <div class="price">¥{{ orderItem.clPrice }}</div>
                    <div class="count">x{{ orderItem.clNum }}</div>
                  </li>
                </ul>
              </div>
              <div class="column state">
                <p style="margin-bottom: 4px">{{ order.statues }}</p>
                <p v-if="order.statues === '待支付'">
                  <el-button text bg @click="pay(order.orderNo)" style="margin: -2px 0 7px">继续支付</el-button>
                  <el-button link @click="cancelOrder(order.orderNo)">取消订单</el-button>
                </p>
                <p v-if="order.statues === '待发货'">
                  <el-button link @click="cancelOrder(order.orderNo)">取消订单</el-button>
                </p>
                <p v-if="order.statues === '待收货'">
                  <el-button text bg @click="receiveOrder(order.orderNo)" style="margin: -2px 0 7px">确认收货</el-button>
                  <el-button link>查看物流</el-button>
                </p>
                <p v-if="order.statues === '待评价'">
                  <el-button link>评价商品</el-button>
                </p>
                <p v-if="order.statues === '已完成'">
                  <el-button link>查看评价</el-button>
                </p>
              </div>
              <div class="column amount">
                <p class="red">¥{{ order.payment?.toFixed(2) }}</p>
                <p>（含运费：¥0.00）</p>

              </div>
              <div class="column action">
                <p><el-button link @click="buyAgain(order.orderItems)">再次购买</el-button></p>
                <p><el-button link>查看详情</el-button></p>
                <p><el-button link>申请售后</el-button></p>
              </div>
            </div>
          </div>
        </el-scrollbar>

      </div>

    </el-tabs>
  </div>
</template>

<style>
.el-tabs__item:hover {
  color: #e180a4;
}

.el-tabs__item.is-active {
  color: #e180a4;
}

.el-tabs__active-bar {
  background-color: #e180a4;
}
.ExitConfirmButton {
  background-color: #ffd2d8;
  color: #333;
  border: none;
}

.ExitConfirmButton:hover {
  background-color: #ffe0e4;
  color: #333;
}
</style>

<style scoped>
.el-button , .el-button:hover {
  color: #e180a4;
  font-size: 15px;
  margin: 3px;
}

.order-container {
  background-color: #fff;
  padding: 20px;

  .pagination-container {
    display: flex;
    justify-content: center;
  }
  
  .main-container {

    a {
      display: block;
      color: #e180a4;
    }

    .holder-container {
      min-height: 500px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}

.order-item {
  margin-bottom: 20px;
  border: 1px solid #f5f5f5;

  .head {
    height: 50px;
    line-height: 50px;
    background: #f5f5f5;
    padding: 0 20px;
    overflow: hidden;

    span {
      margin-right: 20px;

      &.down-time {
        margin-right: 0;
        float: right;

        i {
          vertical-align: middle;
          margin-right: 3px;
        }

        b {
          vertical-align: middle;
          font-weight: normal;
        }
      }
    }

  }

  .body {
    display: flex;
    align-items: stretch;

    .state {
      width: 150px;
    }

    .amount {
      width: 170px;
    }

    .red {
      color: #cf4444;
      font-size: 18px;
      font-weight: bold;
    }

    .column {
      border-left: 1px solid #f5f5f5;
      text-align: center;
      padding: 20px;

      >p {
        padding-top: 10px;
      }

      &:first-child {
        border-left: none;
      }

      &.goods {
        flex: 1;
        padding: 0;
        align-self: center;

        ul {
          li {
            border-bottom: 1px solid #f5f5f5;
            padding: 10px;
            display: flex;

            &:last-child {
              border-bottom: none;
            }

            .goodsItem {
              width: 70px;
              height: 70px;
              border: 1px solid #f5f5f5;

              img {
                width: 70px;
                height: 70px;
                border: 1px solid #f5f5f5;
              }
            }

            .info {
              width: 220px;
              text-align: left;
              padding: 0 10px;

              p {
                margin-bottom: 5px;

                &.name {
                  height: 38px;
                }


                  span {
                    margin-right: 5px;
                  }
                }
              }
            }

            .price {
              width: 100px;
            }

            .count {
              width: 80px;
            }
          }
        }
      }

    }
  }

</style>